package top.infopub.mgr.cap.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.DetailTrackDto;
import top.infopub.dto.mkt.FundingApprovalDto;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.cap.dao.FinancialInstitutionsDao;
import top.infopub.mgr.cap.dao.FundingApprovalDao;
import top.infopub.mgr.cap.dao.InformationSubmitApprovalDao;
import top.infopub.mgr.cap.service.FundingApprovalService;
import top.infopub.mgr.common.cnst.MapKeyComparator;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.impl.CollectProjectServiceImpl;
import top.infopub.model.cap.*;
import top.infopub.model.flow.ProcessNode;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

import java.util.*;


/**
 * @Author Warking
 * @Date 2021/5/23 19:00
 * @Version 1.0 融资批复
 */
@Service
public class FundingApprovalServiceImpl extends GenericFlowController implements FundingApprovalService {

    @Autowired
    private FundingApprovalDao fundingApprovalDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private CollectProjectServiceImpl collectProjectService;
    @Autowired
    private FinancialInstitutionsDao financialInstitutionsDao;
    @Autowired
    private InformationSubmitApprovalDao informationSubmitApprovalDao;

    @Override
    /*融资批复列表接口*/
    public Page<FundingApproval> selectPage(Page<FundingApproval> page, FundingApproval fundingApproval) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return fundingApprovalDao.selectPage(fundingApproval);
    }

    //融资跟踪的详情
    @Override
    public DetailTrackDto queryDetailTrack(String setupFinancialId) {
        DetailTrackDto dto = new DetailTrackDto();
        List<FinancingTracking> list = new ArrayList<>();
        //根据ID查询金融的详情数据
        SetupFinancial setupFinancial = setupFinancialDetail(setupFinancialId);
        //查询跟踪信息的详情
        List<FinancingTracking> financingTrackingList = trackingDetail(setupFinancialId, "9");
        List<FinancingTracking> financingTrackingOne = trackingDetail(setupFinancialId, "0");
        //查询展示项目最新信息
        if (financingTrackingOne != null && financingTrackingOne.size() > 0) {
            dto.setFinancingTracking(financingTrackingOne.get(0));
        }
        for (FinancingTracking financingTracking : financingTrackingList) {
            String status = financingTracking.getProcessStatus();
            if ((!"1".equals(status)) && (!"10".equals(status))) {
                //查询跟踪人员
                String name = fundingApprovalDao.findPersonalById(financingTracking.getAddBy());
                financingTracking.setTrackPeople(name);
                //根据processId流程ID查询并且存放审批意见
                List<ProcessNode> processNodeList = informationSubmitApprovalDao.selectProcessNodeByProcessId(financingTracking.getProcessId());
                financingTracking.setProcessNodeList(processNodeList);
                list.add(financingTracking);
            }
        }
        dto.setSetupFinancial(setupFinancial);
        dto.setFinancingTrackingList(financingTrackingList);
        //登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String personalName = fundingApprovalDao.findPersonalById(vo.getId());
        dto.setName(personalName);
        return dto;
    }

    /*融资跟踪的保存*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(FinancingTracking tracking) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        if (StringUtils.isEmpty(tracking.getId())) {//保存
            //登录人员信息
            tracking.setAddBy(vo.getId());
            tracking.setAddTime(new Date());
            tracking.setProcessStatus("0");
            int i = fundingApprovalDao.insertFinancingTracking(tracking);
            return tracking.getId();
        } else {
            //修改人员信息
            tracking.setUptBy(vo.getId());
            tracking.setUptTime(new Date());
            int i = fundingApprovalDao.updateFinancingTracking(tracking);
            return tracking.getId();
        }

    }

    /*融资金融批复的保存*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveFundingApproval(FundingApproval fundingApproval) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //前端附件信息
        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if (fundingApproval.getFileAtt() != null) {
            String[] fileAtt = fundingApproval.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, fundingApproval.getSetupFinancialId(), file);
                attachmentList.add(attachment);
            }
        }
        //更新附件信息
        projectAttachmentDao.deleteByWhere(fundingApproval.getSetupFinancialId(), ProjectFileTypeEnum.FILE_TYPE47.getCode(), null);
        if (attachmentList.size() > 0 && attachmentList != null) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        //判断是更新还是保存
        if (StringUtils.isEmpty(fundingApproval.getId())) {
            //登录人员信息
            fundingApproval.setAddBy(vo.getId());
            fundingApproval.setAddTime(new Date());
            //保存批复结果数据
            int i = fundingApprovalDao.insertFundingApproval(fundingApproval);
            return i;
        } else {
            //修改人员信息
            fundingApproval.setUptBy(vo.getId());
            fundingApproval.setUptTime(new Date());
            //修改批复结果数据
            int i = fundingApprovalDao.updateFundingApproval(fundingApproval);
            return i;
        }
    }

    /*查询当前批复结果数据的审批状态*/
    @Override
    public FundingApproval findByFundingApprovalId(String id) {
        return fundingApprovalDao.findByFundingApprovalId(id);
    }

    @Override
    public FundingApproval selectByKey(String id) {
        return fundingApprovalDao.findByFundingApprovalId(id);
    }

    /*查询最新的融资跟踪数据*/
    @Override
    public FinancingTracking selectByKeyOrderByTime(String JinRoId) {
        return fundingApprovalDao.selectByKeyOrderByTime(JinRoId);
    }

    //有返回processID 证明提交成功 去往金融机构选择表和其子表写入数据
    //写入前先判断 根据proCode 判断主表有没有数据
    //不管主表有没有数据都要往从表添加数据
    @Override
    public void saveToFinancialInstitutions(FundingApproval reply) {
        String proName = reply.getProName();
        String proCode = reply.getProCode();
        String setupFinancialId = reply.getSetupFinancialId();
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String addBy = vo.getId();
        Date addTime = new Date();
        /*写入前先判断 根据proCode 判断主表有没有数据*/
        FinancialInstitutions financial = financialInstitutionsDao.findByProCode(proCode);
        FinancialElectSublist financialElectSublist = new FinancialElectSublist();
        if (financial == null) {
            //去保存主表数据 ａｎｄ　往子表写数据
            FinancialInstitutions financialInstitutions = new FinancialInstitutions();
            financialInstitutions.setAddBy(addBy);
            financialInstitutions.setAddTime(addTime);
            financialInstitutions.setProName(proName);
            financialInstitutions.setProCode(proCode);
            financialInstitutions.setProcessStatus("0");
            //保存主表数据
            financialInstitutionsDao.saveFinancialInstitutions(financialInstitutions);
            //保存子表数据
            financialElectSublist.setFinancialInstitutionsId(financialInstitutions.getId());
            financialElectSublist.setProCode(proCode);
            financialElectSublist.setProName(proName);
            financialElectSublist.setAddBy(addBy);
            financialElectSublist.setAddTime(addTime);
            financialElectSublist.setProcessStatus("0");
            financialElectSublist.setSetupFinancialId(setupFinancialId);
            //保存子表数据 -- 数据库
            financialInstitutionsDao.saveFinancialElectSublist(financialElectSublist);
        } else {
            //主表 数据 往子表写数据
            //保存子表数据
            financialElectSublist.setFinancialInstitutionsId(financial.getId());
            financialElectSublist.setProCode(proCode);
            financialElectSublist.setProName(proName);
            financialElectSublist.setAddBy(addBy);
            financialElectSublist.setAddTime(addTime);
            financialElectSublist.setProcessStatus("0");
            financialElectSublist.setSetupFinancialId(setupFinancialId);
            //保存子表数据 -- 数据库
            financialInstitutionsDao.saveFinancialElectSublist(financialElectSublist);
        }

    }

    @Override
    public FinancingTracking selectById(String id) {
        return fundingApprovalDao.selectById(id);
    }

    /*融资批复结果的详情*/
    @Override
    public FundingApprovalDto queryDetailFundingApproval(String jinRoSGUID) {
        FundingApprovalDto dto = new FundingApprovalDto();
        //根据ID查询金融的详情数据
        SetupFinancial setupFinancial = setupFinancialDetail(jinRoSGUID);
        //查询跟踪信息的详情
        List<FinancingTracking> financingTrackingList = trackingDetail(jinRoSGUID, "9");
        //去重  getApprovalFinancial()是类型  1，2，3
        ArrayList<FinancingTracking> trackings = new ArrayList<>();
/*      List<FinancingTracking> financingTrackingListDistinct = financingTrackingList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(o -> o.getSkuAttrValueName())))), ArrayList::new);*/
        Map<Integer, FinancingTracking> sortMap = new TreeMap<Integer, FinancingTracking>(
                new MapKeyComparator());
        for (FinancingTracking ft : financingTrackingList) {
            //查询跟踪人员
            String name = fundingApprovalDao.findPersonalById(ft.getAddBy());
            ft.setTrackPeople(name);
            sortMap.put(Integer.valueOf(ft.getApprovalFinancial()), ft);
        }

        for (FinancingTracking ft : sortMap.values()) {
            trackings.add(ft);
        }
        dto.setSetupFinancial(setupFinancial);

        dto.setFinancingTrackingList(trackings);
        //根据金融机构的SGUID查询批复详情数据
        FundingApproval fundingApproval = fundingApprovalDao.selectFundingApprovalByJinRoId(jinRoSGUID);
        dto.setFundingApproval(fundingApproval);
        //附件查询   proCODE不是唯一 所以使用金融ID 当标识
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(jinRoSGUID, ProjectFileTypeEnum.FILE_TYPE47.getCode(), null);
        if (projectAttaList != null && projectAttaList.size() > 0) {
            fundingApproval.setFileAtt(collectProjectService.fileAttaListToArray(projectAttaList));
        }
        return dto;
    }

    /*查询当前的跟踪数据的审批状态*/
    @Override
    public FinancingTracking findById(String id) {
        return fundingApprovalDao.findById(id);
    }


    //公共查询金融机构详情数据的方法
    public SetupFinancial setupFinancialDetail(String JRJGSGUID) {
        return fundingApprovalDao.selectByJinRoJiGouId(JRJGSGUID);
    }

    //公共查询融资跟踪数据的方法 根据金融机构SGUID查询 所有符合的数据
    public List<FinancingTracking> trackingDetail(String setupFinancialSGUID, String processStatus) {
        return fundingApprovalDao.selectProcessStatus(setupFinancialSGUID, processStatus);
    }


}
